#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <functional>
#include<arpa/inet.h>
#include "LOG.hpp"
#include "InetAddr.hpp"
enum
{
    SOCKET_ERROR=1,
    BIND_ERROR,
    USAGE_ERROR
};
const static int defaultsockfd = -1; 
class UdpServer
{
public:
    UdpServer(uint16_t port)//构造
        :_sockfd(defaultsockfd)
        ,_port(port)
        ,_isrunning(false)
    {}
    //服务初始化
    void InitServer()
    {
        //创建套接字
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd<0)//创建失败，日志报错，退出
        {
            LOG(FATAL,"socket error:%s,%d\n",strerror(errno),errno);
            exit(SOCKET_ERROR);
        }
        //创建成功
        LOG(INFO,"socket create success,sockfd:%d\n",_sockfd);

        //填充sockaddr_in结构
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));//清一下结构里面的数据
        local.sin_family=AF_INET;//网络通信
        local.sin_port=htons(_port);//port需要经过网络传输给对面的client，主机序列要先转网络序列
        local.sin_addr.s_addr=INADDR_ANY;

        //bind
        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n<0)//绑定失败
        {
            LOG(FATAL,"bind error,%s:%d\n",strerror(errno),errno);
            exit(BIND_ERROR);
        }
        //绑定成功
        LOG(INFO, "socket bind success\n");
    }
    //开始运行
    void Start()
    {
        _isrunning = true;
        while(_isrunning)//服务一般都是一直运行的死循环
        {
            //接收
            char buffer[1024];
            struct sockaddr_in peer;//client端
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
            if(n > 0)//收到了
            {
                buffer[n]=0;
                InetAddr addr(peer);
                LOG(DEBUG,"服务端从[%s:%d]获取信息:%s\n",addr.Ip().c_str(),addr.Port(),buffer);
                //你收到了才能发嘛
                sendto(_sockfd,buffer,strlen(buffer),0,(struct sockaddr*)&peer,len);
            }

        }
        _isrunning = false;
    }
    ~UdpServer()//析构
    {}
private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;//判断服务端是否运行
};